package st;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;

import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import st.base.Sysdate;
import st.base.UserException;
import st.strategy.vo.GoldenCross;
import st.strategy.vo.Ma;
import st.strategy.vo.Stock;

public class Stk {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		// Load data
		Logger logger = LoggerFactory.getLogger(Stk.class);
		try {
			if (!validateArgs(args)) {
				return;
			}
			File f = new File(DATA_SRC_FP);
			if (!f.exists() || f.isDirectory()) {
				throw new UserException("沒這個檔:" + DATA_SRC_FP);
			}
			String defaultEncoding = "ms950";
			File reportFile = new File("report.txt");
			ArrayList<String> report = new ArrayList<String>();
			List<String> dataLines = FileUtils.readLines(f, defaultEncoding);
			if (dataLines.size() <= 1) {
				throw new UserException("好像沒資料:" + DATA_SRC_FP);
			}
			Collection<BasicStockData> stockTradeDatas = new ArrayList<BasicStockData>();
			// 讀取單一股票資訊
			String DATE_PATERN = "yyyy/M/d";
			SimpleDateFormat sdf = new SimpleDateFormat(DATE_PATERN);
			String stockId = "2330";
			Stock stock = new Stock(stockId);
			Collection<Sysdate> tradeDates = new LinkedHashSet<Sysdate>();
			for (int i = 1; i < dataLines.size(); i++) {
				String dataLine = dataLines.get(i);
				String[] columns = dataLine.split(",");
				Calendar tradeDateC = Calendar.getInstance();
				tradeDateC.clear();
				Date _date = sdf.parse(columns[0]);
				String dateStr = DateFormatUtils.format(_date,
						Sysdate.KEY_DATE_PATERN);
				dateStr = dateStr.replaceAll("/", "");
				Sysdate tradeDate = Sysdate.getInstance(dateStr);
				tradeDates.add(tradeDate);
				BasicStockData std = new BasicStockData(stock, tradeDate,
						Double.parseDouble(columns[1]),
						Double.parseDouble(columns[2]),
						Double.parseDouble(columns[3]),
						Double.parseDouble(columns[4]));
				stockTradeDatas.add(std);
			}
			Ma _2303_5 = new Ma(stock, stockTradeDatas, 5);
			_2303_5.build();
			Ma _2303_10 = new Ma(stock, stockTradeDatas, 10);
			_2303_10.build();
			Collection<Sysdate> testSysdates = Sysdate.getInstanceBetween(
					"20130531", "20131011");
			for (Sysdate tradeDate : testSysdates) {
				if (tradeDates.contains(tradeDate)) {
					GoldenCross gc = new GoldenCross(_2303_10, _2303_5,
							tradeDate, stock);
					if (gc.isAppear()) {
						logger.debug("{} {} 發生黃金5-10交叉", stockId,
								tradeDate.getString());
					}
				}
			}
			FileUtils.writeLines(reportFile, defaultEncoding, report);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static boolean validateArgs(String[] args) throws ParseException {
		BasicParser parser = new BasicParser();
		Options ops = new Options();
		Option opt = new Option("f", true, "完整的路徑+檔名");
		opt.setArgName("檔名");
		ops.addOption(opt);
		HelpFormatter formatter = new HelpFormatter();
		CommandLine cmd = parser.parse(ops, args);
		DATA_SRC_FP = cmd.getOptionValue('f');
		if (DATA_SRC_FP == null) {
			formatter.printHelp("help", ops, true);
			return false;
		}
		return true;

	}

	private static String DATA_SRC_FP;
	public static double INIT_CAP = 100000;

}
